'''
@Descripttion: 
@version: 
@encoding: utf-8
@Author: qiurongcan
Date: 2025-09-29 16:49:38
LastEditTime: 2025-09-29 17:01:34
'''



class Solution:

    # 用一个栈存储还是比较容易理解的
    def reverseKGroup(self, head, k):
        n = 0
        cur = head

        while cur:
            n += 1
            cur = cur.next

        p0 = dummy = ListNode(next=head)
        pre = None
        cur = head

        while n >= k:
            n -= k

            stack = []
            for _ in range(k):

                stack.append(cur)
                cur = cur.next
            
            temp = cur

            for _ in range(k):
                p0.next = stack.pop()
                p0 = p0.next
            
            p0.next = temp

        return dummy.next
            





